package com.itggm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itggm.Result.ResponseResult;
import com.itggm.dto.AddRolePermissionsDTO;
import com.itggm.dto.RolePageDTO;
import com.itggm.mapper.PermissionMapper;
import com.itggm.mapper.RolePermissionMapper;
import com.itggm.mapper.UserRoleMapper;
import com.itggm.pojo.Permission;
import com.itggm.pojo.Role;
import com.itggm.pojo.RolePermission;
import com.itggm.pojo.UserRole;
import com.itggm.service.RoleService;
import com.itggm.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author root
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-12-21 11:48:02
*/
@Transactional
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{


    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult rolePage(RolePageDTO rolePageDTO) {
        //构建分页对象
        Page<Role> rolePage = new Page<>(rolePageDTO.getPage(),rolePageDTO.getLimit());
        //构建分页条件
        String roleEn = rolePageDTO.getRoleEn();
        String roleCh = rolePageDTO.getRoleCh();
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(roleCh),Role::getRoleCh,roleCh)
                .like(StringUtils.isNotBlank(roleEn),Role::getRoleEn,roleEn);
        //执行分页
        baseMapper.selectPage(rolePage,wrapper);
        //返回分页结果
        return ResponseResult.success()
                .data("total",rolePage.getTotal())
                .data("tableData",rolePage.getRecords());
    }

    @Override
    public ResponseResult delete(Integer rid) {

        //先角色权限是否被关联

        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,rid);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (ObjectUtils.isNotNull(userRoles)){
            return  ResponseResult.fail().message("角色被关联，请联系管理员删除");
        }

        //2. 删除角色信息
        baseMapper.deleteById(rid);

        // 3.删除角色对应的权限
        LambdaQueryWrapper<RolePermission> lambda1 = new QueryWrapper<RolePermission>().lambda();
        lambda1.eq(RolePermission::getRoleId,rid);
        rolePermissionMapper.delete(lambda1);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult rolePermissions(Integer id) {
        // 根据角色id  查询角色权限id  role_permission
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,id);

        Set<Integer> pIds = rolePermissionMapper.selectList(lambda)
                .stream().map(rp -> rp.getPerId())
                .collect(Collectors.toSet());

        if (ObjectUtils.isNull(pIds)){
            return ResponseResult.success()
                    .data("isMenuIds",new ArrayList<>());
        }

        LambdaQueryWrapper<Permission> lambda1 = new QueryWrapper<Permission>().lambda();
        lambda1.in(Permission::getId,pIds)
                .eq(Permission::getIsMenu,2);

        List<Integer> isMenuIds = permissionMapper.selectList(lambda1)
                .stream().map(permission -> permission.getId())
                .collect(Collectors.toList());

        return ResponseResult.success()
                .data("isMenuIds",isMenuIds);
    }
    @Override
    public ResponseResult addRolePermissions(AddRolePermissionsDTO addRolePermissionsDTO) {

        List<Integer> pIds  = addRolePermissionsDTO.getNewKeys();
        Integer rid = addRolePermissionsDTO.getRid();

        // 根据角色id  删除角色又有的权限信息
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,rid);
        rolePermissionMapper.delete(lambda);

        // 添加角色新权限

       /* pIds.forEach(pid->{
            RolePermission rolePermission = new RolePermission(rid, pid);
            rolePermissionMapper.insert(rolePermission);
        });*/
        for (Integer pId : pIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(rid);
            rolePermission.setPerId(pId);
            rolePermissionMapper.insert(rolePermission);
        }

        return ResponseResult.success();
    }

}




